from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String, Boolean
from werkzeug.security import generate_password_hash, check_password_hash


class User:
    @staticmethod
    def init_db(db: SQLAlchemy):
        class UserModel(db.Model):
            __tablename__ = 'users'
            
            id = Column(Integer, primary_key=True)
            name = Column(String(80), nullable=False)
            email = Column(String(120), unique=True, nullable=False)
            password_hash = Column(String(128), nullable=False)
            is_admin = Column(Boolean, default=False, nullable=False)
            
            def __repr__(self):
                return f'<User {self.name}>'
            
            @property
            def password(self):
                raise AttributeError('password is not a readable attribute')
            
            @password.setter
            def password(self, password):
                self.password_hash = generate_password_hash(password)
                
            def verify_password(self, password):
                return check_password_hash(self.password_hash, password)
            
            def to_dict(self):
                return {
                    'id': self.id,
                    'name': self.name,
                    'email': self.email,
                    'is_admin': self.is_admin
                }
        
        return UserModel